<template>
    <div class="container yuan-container agency-list">

        <a-card title="门店通用券">
            <a-tabs type="card" :default-active-key="rawTypeKey" @change="tabChange">
                <a-tab-pane key="1" tab="我发起的"></a-tab-pane>
                <a-tab-pane key="2" tab="我参与的"></a-tab-pane>
            </a-tabs>

            <div class="filter-panel">
                <div class="filter-list">
                    <span>关键字：</span>
                    <a-input-search allowClear v-model="pageParams.keyword" placeholder="优惠券编码/名称/创建人" @search="resetList" />
                </div>
                <div class="filter-list">
                    <span>创建时间：</span>
                    <a-range-picker @change="dateChange" :placeholder="['开始日期','结束日期']" :format="['YYYY-MM-DD','YYYY-MM-DD']" />
                </div>
                <div class="filter-list">
                    <span>发放方式：</span>
                    <a-select v-model="pageParams.issueType" @change="resetList" allowClear placeholder="发放方式">
                        <a-select-option value="1">用户主动领取</a-select-option>
                        <a-select-option value="2">系统自动发放</a-select-option>
                    </a-select>
                </div>
                <div class="filter-list">
                    <span>状态：</span>
                    <a-select v-model="pageParams.status" @change="resetList" allowClear placeholder="状态">
                        <a-select-option :value="item.id" v-for="item in statusList"
                            :key="item.id">{{item.name}}</a-select-option>
                    </a-select>
                </div>

                <div style="float:right" class="filter-list" v-if="rawTypeKey==='1'">
                    <a-button type="primary" @click="add" v-if="$checkPer(['organCouponAdd'])">新增</a-button>
                </div>

            </div>
            <div class="table">
                <a-table bordered :loading="loading" :rowKey="(item,i)=>item.id" :columns="columns" :data-source="pageList"
                    :pagination="pagination">
                    <template slot='action' slot-scope="text, record, index">
                        <div v-if="rawTypeKey==='1'">
                            <!-- 我发起的 -->
                            <template v-if="$checkPer(['organCouponOperation'])">
                                <a-popconfirm okText="确定" cancelText="取消" title="确定要发起门店确认吗？" @confirm="clickSendSure(record)"
                                    v-if="record.status===0">
                                    <span class="tab-act c-success">发起门店确认</span>
                                </a-popconfirm>
                                <template v-if="record.status!==0">
                                    <a-popconfirm okText="确定" cancelText="取消" title="确定要重新生成该活动吗？" @confirm="clickCopy(record)">
                                        <span class="tab-act c-warning">重新生成活动</span>
                                    </a-popconfirm>
                                </template>

                                <a-popconfirm okText="确定" cancelText="取消" title="确定要发布该活动吗？" @confirm="clickRelease(record)"
                                    v-if="record.status===3">
                                    <span class="tab-act c-danger">发布</span>
                                </a-popconfirm>
                                <a-popconfirm okText="确定" cancelText="取消" title="确定要下架该活动吗？" @confirm="clickBan(record)"
                                    v-if="record.status===4">
                                    <span class="tab-act c-danger">下架</span>
                                </a-popconfirm>

                                <a-popconfirm okText="确定" cancelText="取消" title="确定要重新发布该活动吗？" @confirm="clickRepublish(record)"
                                    v-if="record.status===5">
                                    <span class="tab-act c-danger">重新发布</span>
                                </a-popconfirm>

                                <a-popconfirm okText="确定" cancelText="取消" title="确定要中止该活动吗？" @confirm="clickDiscontinue(record)"
                                    v-if="record.status===2 || record.status===3 || record.status===5">
                                    <span class="tab-act c-danger">中止活动</span>
                                </a-popconfirm>
                                <template v-if="record.status===0 || record.status===7">
                                    <span class="tab-act c-warning" @click="clickEdit(record)">编辑</span>
                                    <a-popconfirm okText="确定" cancelText="取消" title="确定删除吗？" @confirm="clickDelete(record)"
                                        v-if="$checkPer(['organCouponDelete'])">
                                        <span class="tab-act c-danger">删除</span>
                                    </a-popconfirm>
                                </template>
                            </template>

                            <span class="tab-act c-primary" @click="clickDetail(record)">详情</span>
                            <template v-if="record.status===4 || record.status===5 || record.status===6">
                                <span class="tab-act c-success" @click="clickUseDetail(record)">使用情况</span>
                            </template>

                            <span class="tab-act c-warning" @click="clickDisInfo(record)" v-if="record.status===6">中止原因</span>

                            <span class="tab-act c-primary" @click="clickCouponLink(record)"
                                v-if="record.issueType===1&&record.status===4">活动链接</span>

                            <span class="tab-act c-warning" @click="clickAuditInfo(record)" v-if="record.status===7">驳回原因</span>

                        </div>
                        <div v-if="rawTypeKey==='2'">
                            <!-- 我参与的 -->
                            <template v-if="$checkPer(['organCouponOperation'])">
                                <template v-if="record.status===1 && record.participationStatus===0">
                                    <a-popconfirm okText="确定" cancelText="取消" title="确定要参与该活动吗？" @confirm="clickJoin(record)">
                                        <span class="tab-act c-success">参与</span>
                                    </a-popconfirm>
                                    <span class="tab-act c-danger" @click="clickRefuse(record)">拒绝</span>
                                </template>

                            </template>
                            <span class="tab-act c-primary" @click="clickDetail(record)">详情</span>

                            <template v-if="record.status===1 && record.participationStatus===2">

                                <span class="tab-act c-warning" @click="clickRefuseInfo(record)">拒绝原因</span>
                            </template>

                            <span class="tab-act c-warning" @click="clickDisInfo(record)" v-if="record.status===6">中止原因</span>

                            <span class="tab-act c-primary" @click="clickCopyLink(record)"
                                v-if="record.issueType===1&&record.status===4">复制活动链接</span>

                            <span class="tab-act c-warning" @click="clickAuditInfo(record)" v-if="record.status===7">驳回原因</span>
                        </div>
                    </template>
                </a-table>
            </div>
        </a-card>
        <AddVue :visible="addVisible" @closeModal="() => addVisible = false" @resetList="resetList" :editInfo="editInfo"
            generateType="ORGAN" />
        <DetailVue :visible="detailVisible" @closeModal="() => detailVisible = false" :editInfo="editInfo" :isShow="isShow"
            @resetList="resetList" />
        <UseDetailVue :visible="useDetailVisible" @closeModal="() => useDetailVisible = false" :editInfo="editInfo"
            @resetList="resetList" :couponType="'通用券'" />

        <a-modal width="600px" title="拒绝原因" :visible="refuseVisible" @ok="refuseOk" @cancel="()=>refuseVisible=false" okText="确定"
            cancelText="取消">
            <a-spin tip="Loading..." :spinning="refuseLoading">
                <a-form-model layout="inline" class="yuan-form" :label-col="{ style: { width: '100px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 120px)' } }">
                    <div class="form-panel">

                        <a-form-model-item label="拒绝原因">
                            <a-input v-model="rejectCause" type="textarea" style="width: 500px;" :rows="5" placeholder="请输入拒绝原因"
                                :maxLength="500" />
                        </a-form-model-item>
                    </div>
                </a-form-model>
            </a-spin>
        </a-modal>
        <ShowInfoModalVue :visible="infoVisible" :info="infoData" title="拒绝原因" @cancel="()=>infoVisible=false" />
        <CouponLinkSettingVue :visible="couponLinkVisible" :info="couponLinkData" @closeModal="()=>couponLinkVisible=false" />
        <a-modal width="600px" title="中止原因" :visible="discontinueVisible" @ok="discontinueOk"
            @cancel="()=>discontinueVisible=false" okText="确定" cancelText="取消">
            <a-spin tip="Loading..." :spinning="discontinueLoading">
                <a-form-model layout="inline" class="yuan-form" :label-col="{ style: { width: '100px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 120px)' } }">
                    <div class="form-panel">

                        <a-form-model-item label="中止原因">
                            <a-input v-model="discontinueCause" type="textarea" style="width: 500px;" :rows="5"
                                placeholder="请输入中止原因" :maxLength="500" />
                        </a-form-model-item>
                    </div>
                </a-form-model>
            </a-spin>
        </a-modal>
    </div>
</template>
<script lang="ts">
import api from "@/api/api";
import { Component, Vue } from "vue-property-decorator";
import DetailVue from "../platCoupon/generalDetail.vue";
import AddVue from "../platCoupon/generalAdd.vue";
import UseDetailVue from "../reconciliation/detail.vue";
import marketApi from "@/api/marketApi";
import { format, getStorageUserInfo } from "@/utils";
import { h } from "vue";
import ShowInfoModalVue from "@/components/showInfoModal.vue";
import CouponLinkSettingVue from "@/components/couponLinkSetting.vue";
@Component({
    name: "tpl",
    components: { DetailVue, AddVue, UseDetailVue, ShowInfoModalVue, CouponLinkSettingVue },
})
export default class extends Vue {
    loading = false;
    infoData = "";
    infoVisible = false;
    statusList = [
        { id: 0, name: "待提交", class: "" },
        { id: 1, name: "待确认", class: "c-primary" },
        { id: 2, name: "待审核", class: "c-warning" },
        { id: 3, name: "待发布", class: "c-primary" },
        { id: 4, name: "已发布", class: "c-success" },
        { id: 5, name: "已下架", class: "c-danger" },
        { id: 6, name: "已中止", class: "c-danger" },
        { id: 7, name: "已驳回", class: "c-danger" },
    ];
    pageList = [];
    pagination = {
        current: 1,
        pageSize: 10,
        total: 0,
        onChange: this.pageChange,
    };
    pageParams: any = {
        keyword: "",
    };
    columns = [
        {
            align: "center",
            dataIndex: "couponCode",
            key: "couponCode",
            title: "优惠券编码",
        },
        {
            align: "center",
            dataIndex: "name",
            key: "name",
            title: "优惠券名称",
        },
        {
            align: "center",
            dataIndex: "issueType",
            key: "issueType",
            title: "发放方式",
            customRender: (text: string, record: any, index: number) => {
                return record.issueType === 1 ? "用户主动领取" : "系统自动发放";
            },
        },
        // {
        //     align: "center",
        //     dataIndex: "issueQuantity",
        //     key: "issueQuantity",
        //     title: "发放数量",
        // },
        // {
        //     align: "center",
        //     dataIndex: "receivedQuantity",
        //     key: "receivedQuantity",
        //     title: "领取数量",
        // },
        // {
        //     align: "center",
        //     dataIndex: "usedQuantity",
        //     key: "usedQuantity",
        //     title: "使用数量",
        // },
        {
            align: "center",
            dataIndex: "createTime",
            key: "createTime",
            title: "创建时间",
            customRender: (text: string, record: any, index: number) => {
                return format(record.createTime);
            },
        },
        {
            align: "center",
            dataIndex: "creatorName",
            key: "creatorName",
            title: "创建人",
        },
        {
            align: "center",
            dataIndex: "pageTable9",
            key: "pageTable9",
            title: "参与门店确认进度",
            customRender: (text: string, record: any, index: number) => {
                const left = h("span", { class: "c-success" }, record.participationNum + "/");
                const right = h("span", { class: "c-danger" }, record.sumNum);
                return h("div", [left, right]);
            },
        },
        {
            align: "center",
            dataIndex: "status",
            key: "status",
            title: "状态",
            customRender: (text: string, record: any, index: number) => {
                if (record.status === 2 && record.auditStatus === 2) {
                    //如果是待审核且被拒绝
                    return h("span", { class: "c-danger" }, "审核拒绝");
                }
                const findData = this.statusList.find((item) => {
                    return item.id === record.status;
                });
                if (findData) {
                    return h("span", { class: findData.class }, findData.name);
                }
                return "";
            },
        },

        {
            align: "center",
            dataIndex: "action",
            key: "action",
            title: "操作",
            width: 230,
            scopedSlots: { customRender: "action" },
        },
    ];
    async getList() {
        this.pageList = [];
        this.loading = true;
        try {
            const res = await marketApi.findOwnCouponList({
                ...this.pageParams,
                pageSize: this.pagination.pageSize,
                pageNum: this.pagination.current,
                type: "通用券",
                generalCouponType: this.rawTypeKey,
            });
            this.pageList = res.data?.rows || [];
            this.pagination.total = res.data?.total || 0;
        } finally {
            this.loading = false;
        }
    }
    resetList() {
        this.pagination.current = 1;
        this.getList();
    }
    pageChange(page: number, pageSize: number) {
        this.pagination.pageSize = pageSize;
        this.pagination.current = page;
        this.getList();
    }

    mounted() {
        this.getList();
    }

    isShow = false;
    detailVisible = false;
    addVisible = false;
    add() {
        this.isShow = false;
        this.editInfo = {};
        this.addVisible = true;
    }
    editInfo = {};
    async clickDetail(item) {
        this.loading = true;
        try {
            const res = await marketApi.findCouponDetail(item.id);
            this.isShow = true;
            this.editInfo = res.data;
            this.detailVisible = true;
        } finally {
            this.loading = false;
        }
    }
    async clickEdit(item) {
        this.loading = true;
        try {
            const res = await marketApi.findCouponDetail(item.id);
            this.editInfo = res.data;
            this.addVisible = true;
            this.isShow = false;
        } finally {
            this.loading = false;
        }
    }

    async clickDelete(item) {
        this.loading = true;
        try {
            await marketApi.deleteCoupon(item.id);
            this.$message.success("删除成功");
            this.getList();
        } finally {
            this.loading = false;
        }
    }
    dateChange(e: any[]) {
        const arr = e.map((item) => item.format("YYYY-MM-DD"));
        this.pageParams.createStartTime = arr[0] + " 00:00:01";
        this.pageParams.createEndTime = arr[1] + " 23:59:59";
        this.resetList();
    }
    rawTypeKey = "1";
    tabChange(e: string) {
        this.rawTypeKey = e;
        this.resetList();
    }

    useDetailVisible = false;
    clickUseDetail(item) {
        this.editInfo = item;
        this.useDetailVisible = true;
    }

    async clickSendSure(item) {
        this.loading = true;
        try {
            await marketApi.sponsorStoreAffirm(item.id);
            this.$message.success("发起确认成功");
            this.getList();
        } finally {
            this.loading = false;
        }
    }

    refuseVisible = false;
    refuseLoading = false;
    refuseData: any = {};
    rejectCause = "";
    async clickRefuse(item) {
        this.rejectCause = "";
        this.refuseVisible = true;
        this.refuseData = item;
    }
    async refuseOk() {
        this.refuseLoading = true;
        try {
            const res = await marketApi.participationActivity({
                id: this.refuseData.id,
                refuseCause: this.rejectCause,
                participationStatus: 2,
            });
            this.refuseVisible = false;
            this.$message.success("拒绝成功");
            this.getList();
        } finally {
            this.refuseLoading = false;
        }
    }
    async clickJoin(item) {
        this.loading = true;
        try {
            await marketApi.participationActivity({
                id: item.id,
                participationStatus: 1,
                refuseCause: "",
            });
            this.$message.success("参与成功");
            this.getList();
        } finally {
            this.loading = false;
        }
    }
    async clickCopy(item) {
        this.loading = true;
        try {
            await marketApi.anewGenerateActivity(item.id);
            this.$message.success("重新生成成功");
            this.getList();
        } finally {
            this.loading = false;
        }
    }
    clickRefuseInfo(item) {
        this.infoVisible = true;
        this.showInfoTitle = "拒绝原因";
        this.infoData = item.refuseCause;
    }
    showInfoTitle = "";
    clickAuditInfo(item) {
        this.infoVisible = true;
        this.showInfoTitle = "拒绝原因";
        this.infoData = item.rejectReason;
    }
    clickDisInfo(item) {
        this.infoVisible = true;
        this.showInfoTitle = "中止原因";
        this.infoData = item.suspendCause;
    }

    async clickRelease(item) {
        this.loading = true;
        try {
            await marketApi.updateCouponStatus({
                id: item.id,
                status: 4,
                suspendCause: "",
            });
            this.$message.success("发布成功");
            this.getList();
        } finally {
            this.loading = false;
        }
    }
    async clickBan(item) {
        this.loading = true;
        try {
            await marketApi.updateCouponStatus({
                id: item.id,
                status: 5,
                suspendCause: "",
            });
            this.$message.success("下架成功");
            this.getList();
        } finally {
            this.loading = false;
        }
    }
    async clickRepublish(item) {
        this.loading = true;
        try {
            await marketApi.updateCouponStatus({
                id: item.id,
                status: 4,
                suspendCause: "",
            });
            this.$message.success("重新上架成功");
            this.getList();
        } finally {
            this.loading = false;
        }
    }

    discontinueVisible = false;
    discontinueCause = "";
    discontinueLoading = false;
    discontinueData: any = {};
    clickDiscontinue(item) {
        this.discontinueData = item;
        this.discontinueVisible = true;
    }
    async discontinueOk() {
        this.discontinueLoading = true;
        const res = await marketApi.updateCouponStatus({
            id: this.discontinueData.id,
            status: 6,
            suspendCause: this.discontinueCause,
        });
        this.discontinueLoading = false;
        this.discontinueVisible = false;
        this.$message.success(res.msg);
        this.getList();
    }
    couponLinkVisible = false;
    couponLinkData = {};
    clickCouponLink(item) {
        this.couponLinkData = item;
        this.couponLinkVisible = true;
    }

    async clickCopyLink(item) {
        const userInfo = getStorageUserInfo();
        try {
            await navigator.clipboard.writeText(location.origin + "/#/couponLink?id=" + item.id + "&storeId=" + userInfo.id);
            this.$message.success("复制成功");
        } catch (err) {
            this.$message.error("复制失败，请检查浏览器权限");
        }
    }
}
</script>
<style scoped lang="scss">
.agency-list {
    .showInfobox {
        display: inline-block;
        width: 468px;
        background: #eee;
        padding: 0 10px;
        border-radius: 8px;
    }
}
</style>
